// 获取DOM元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const startBtn = document.getElementById('start-btn');
const pauseBtn = document.getElementById('pause-btn');
const resetBtn = document.getElementById('reset-btn');

// 游戏常量
const GRID_SIZE = 20;
const CANVAS_WIDTH = canvas.width;
const CANVAS_HEIGHT = canvas.height;
const GRID_WIDTH = CANVAS_WIDTH / GRID_SIZE;
const GRID_HEIGHT = CANVAS_HEIGHT / GRID_SIZE;

// 游戏变量
let snake = [];
let food = {};
let direction = '';
let nextDirection = '';
let score = 0;
let gameInterval;
let gameSpeed = 150; // 毫秒
let isGameRunning = false;
let gameOver = false;

// 初始化游戏
function initGame() {
    // 重置蛇的位置和长度
    snake = [
        { x: 10, y: 10 },
        { x: 9, y: 10 },
        { x: 8, y: 10 }
    ];
    
    // 随机生成食物位置
    generateFood();
    
    // 重置游戏状态
    direction = 'right';
    nextDirection = 'right';
    score = 0;
    scoreElement.textContent = score;
    gameOver = false;
    
    // 绘制初始状态
    draw();
}

// 生成食物
function generateFood() {
    let newFood;
    let foodOnSnake = true;
    
    // 确保食物不会出现在蛇身上
    while (foodOnSnake) {
        newFood = {
            x: Math.floor(Math.random() * GRID_WIDTH),
            y: Math.floor(Math.random() * GRID_HEIGHT)
        };
        
        foodOnSnake = snake.some(segment => segment.x === newFood.x && segment.y === newFood.y);
    }
    
    food = newFood;
}

// 更新游戏状态
function update() {
    if (!isGameRunning || gameOver) return;
    
    // 更新方向
    direction = nextDirection;
    
    // 获取蛇头位置
    const head = { ...snake[0] };
    
    // 根据方向移动蛇头
    switch (direction) {
        case 'up':
            head.y -= 1;
            break;
        case 'down':
            head.y += 1;
            break;
        case 'left':
            head.x -= 1;
            break;
        case 'right':
            head.x += 1;
            break;
    }
    
    // 检查碰撞
    if (checkCollision(head)) {
        gameOver = true;
        clearInterval(gameInterval);
        alert('游戏结束！最终得分：' + score);
        return;
    }
    
    // 将新头添加到蛇身上
    snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        // 增加分数
        score += 10;
        scoreElement.textContent = score;
        
        // 生成新食物
        generateFood();
        
        // 随着分数增加，游戏速度加快
        if (score % 50 === 0 && gameSpeed > 50) {
            gameSpeed -= 10;
            clearInterval(gameInterval);
            gameInterval = setInterval(update, gameSpeed);
        }
    } else {
        // 如果没吃到食物，移除尾部
        snake.pop();
    }
    
    // 绘制更新后的游戏状态
    draw();
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    
    // 绘制蛇
    snake.forEach((segment, index) => {
        ctx.fillStyle = index === 0 ? '#0095DD' : '#0066AA';
        ctx.fillRect(segment.x * GRID_SIZE, segment.y * GRID_SIZE, GRID_SIZE - 1, GRID_SIZE - 1);
        
        // 为蛇头添加眼睛
        if (index === 0) {
            ctx.fillStyle = 'white';
            const eyeSize = GRID_SIZE / 5;
            const eyeOffset = GRID_SIZE / 3;
            
            if (direction === 'right') {
                ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset, segment.y * GRID_SIZE + eyeOffset, eyeSize, eyeSize);
                ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset * 2, eyeSize, eyeSize);
            } else if (direction === 'left') {
                ctx.fillRect(segment.x * GRID_SIZE + eyeOffset - eyeSize, segment.y * GRID_SIZE + eyeOffset, eyeSize, eyeSize);
                ctx.fillRect(segment.x * GRID_SIZE + eyeOffset - eyeSize, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset * 2, eyeSize, eyeSize);
            } else if (direction === 'up') {
                ctx.fillRect(segment.x * GRID_SIZE + eyeOffset, segment.y * GRID_SIZE + eyeOffset - eyeSize, eyeSize, eyeSize);
                ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset * 2, segment.y * GRID_SIZE + eyeOffset - eyeSize, eyeSize, eyeSize);
            } else if (direction === 'down') {
                ctx.fillRect(segment.x * GRID_SIZE + eyeOffset, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset, eyeSize, eyeSize);
                ctx.fillRect(segment.x * GRID_SIZE + GRID_SIZE - eyeOffset * 2, segment.y * GRID_SIZE + GRID_SIZE - eyeOffset, eyeSize, eyeSize);
            }
        }
    });
    
    // 绘制食物
    ctx.fillStyle = '#FF4444';
    ctx.fillRect(food.x * GRID_SIZE, food.y * GRID_SIZE, GRID_SIZE - 1, GRID_SIZE - 1);
    
    // 如果游戏结束，显示游戏结束文本
    if (gameOver) {
        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        ctx.fillStyle = 'white';
        ctx.font = '24px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('游戏结束！', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 - 15);
        ctx.font = '16px Arial';
        ctx.fillText('按重置按钮重新开始', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 + 15);
    }
    
    // 如果游戏暂停，显示暂停文本
    if (!isGameRunning && !gameOver) {
        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
        ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        ctx.fillStyle = 'white';
        ctx.font = '24px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('游戏暂停', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2);
    }
}

// 检查碰撞
function checkCollision(head) {
    // 检查是否撞到墙壁
    if (head.x < 0 || head.x >= GRID_WIDTH || head.y < 0 || head.y >= GRID_HEIGHT) {
        return true;
    }
    
    // 检查是否撞到自己的身体
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            return true;
        }
    }
    
    return false;
}

// 开始游戏
function startGame() {
    if (!isGameRunning && !gameOver) {
        isGameRunning = true;
        gameInterval = setInterval(update, gameSpeed);
    }
}

// 暂停游戏
function pauseGame() {
    if (isGameRunning && !gameOver) {
        isGameRunning = false;
        clearInterval(gameInterval);
        draw(); // 重绘以显示暂停文本
    }
}

// 重置游戏
function resetGame() {
    clearInterval(gameInterval);
    initGame();
}

// 处理键盘输入
function handleKeyDown(e) {
    // 防止页面滚动
    if ([37, 38, 39, 40, 32, 87, 83, 65, 68].includes(e.keyCode)) {
        e.preventDefault();
    }
    
    // 根据按键设置下一个方向
    switch (e.keyCode) {
        case 38: // 上箭头
        case 87: // W键
            if (direction !== 'down') {
                nextDirection = 'up';
            }
            break;
        case 40: // 下箭头
        case 83: // S键
            if (direction !== 'up') {
                nextDirection = 'down';
            }
            break;
        case 37: // 左箭头
        case 65: // A键
            if (direction !== 'right') {
                nextDirection = 'left';
            }
            break;
        case 39: // 右箭头
        case 68: // D键
            if (direction !== 'left') {
                nextDirection = 'right';
            }
            break;
        case 32: // 空格键
            if (gameOver) {
                resetGame();
            } else if (isGameRunning) {
                pauseGame();
            } else {
                startGame();
            }
            break;
    }
}

// 添加触摸支持（移动设备）
let touchStartX = 0;
let touchStartY = 0;

function handleTouchStart(e) {
    touchStartX = e.touches[0].clientX;
    touchStartY = e.touches[0].clientY;
}

function handleTouchMove(e) {
    if (!touchStartX || !touchStartY) return;
    
    const touchEndX = e.touches[0].clientX;
    const touchEndY = e.touches[0].clientY;
    
    const diffX = touchStartX - touchEndX;
    const diffY = touchStartY - touchEndY;
    
    // 确定滑动方向
    if (Math.abs(diffX) > Math.abs(diffY)) {
        // 水平滑动
        if (diffX > 0 && direction !== 'right') {
            nextDirection = 'left';
        } else if (diffX < 0 && direction !== 'left') {
            nextDirection = 'right';
        }
    } else {
        // 垂直滑动
        if (diffY > 0 && direction !== 'down') {
            nextDirection = 'up';
        } else if (diffY < 0 && direction !== 'up') {
            nextDirection = 'down';
        }
    }
    
    // 重置触摸起始位置
    touchStartX = touchEndX;
    touchStartY = touchEndY;
}

function handleTouchEnd() {
    touchStartX = null;
    touchStartY = null;
}

// 为移动设备添加虚拟方向按钮
function createVirtualButtons() {
    // 仅在移动设备上添加虚拟按钮
    if (window.innerWidth <= 768) {
        const buttonsContainer = document.createElement('div');
        buttonsContainer.className = 'virtual-buttons';
        buttonsContainer.innerHTML = `
            <button class="btn-up" data-direction="up">↑</button>
            <div class="horizontal-buttons">
                <button class="btn-left" data-direction="left">←</button>
                <button class="btn-down" data-direction="down">↓</button>
                <button class="btn-right" data-direction="right">→</button>
            </div>
        `;
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .virtual-buttons {
                margin-top: 20px;
                position: relative;
                width: 200px;
                height: 200px;
                margin-left: auto;
                margin-right: auto;
            }
            .btn-up,
            .btn-down,
            .btn-left,
            .btn-right {
                position: absolute;
                width: 60px;
                height: 60px;
                font-size: 24px;
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 10px;
                cursor: pointer;
                box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            }
            .btn-up {
                top: 0;
                left: 70px;
            }
            .horizontal-buttons {
                position: absolute;
                top: 70px;
                left: 0;
                width: 200px;
                display: flex;
                justify-content: space-between;
            }
            .btn-down {
                top: 140px;
                left: 70px;
            }
        `;
        
        document.body.appendChild(style);
        document.querySelector('.game-container').appendChild(buttonsContainer);
        
        // 添加按钮事件监听
        document.querySelectorAll('.virtual-buttons button').forEach(button => {
            button.addEventListener('touchstart', (e) => {
                e.preventDefault();
                const newDirection = button.dataset.direction;
                // 确保不会立即反向移动
                if ((direction === 'up' && newDirection !== 'down') ||
                    (direction === 'down' && newDirection !== 'up') ||
                    (direction === 'left' && newDirection !== 'right') ||
                    (direction === 'right' && newDirection !== 'left')) {
                    nextDirection = newDirection;
                }
            });
        });
    }
}

// 添加事件监听
startBtn.addEventListener('click', startGame);
pauseBtn.addEventListener('click', pauseGame);
resetBtn.addEventListener('click', resetGame);
window.addEventListener('keydown', handleKeyDown);

// 触摸事件监听
canvas.addEventListener('touchstart', handleTouchStart, { passive: false });
canvas.addEventListener('touchmove', handleTouchMove, { passive: false });
canvas.addEventListener('touchend', handleTouchEnd);

// 初始化游戏和创建虚拟按钮
initGame();
createVirtualButtons();